library(tidyverse)
library(ggpubr)
library(CytoExploreR)

# set work directory because config file will be automatically write in root of work directory
setwd("~/文档/liulab-data-analysis/00_util_scripts/CytometRy/230510/")

# setup compensation control ---------
compenSet <- cyto_setup("comp/",
                        gatingTemplate = "comp/tempalate.csv"
)

# Transform fluorescent channels - default logicle transformations
compenSet <- cyto_transform(compenSet)

# Gate Cells
cyto_gate_draw(compenSet,
               parent = "root",
               alias = "Cells",
               channels = c("FSC-A", "SSC-A")
)

# Gate single Cells
cyto_gate_draw(compenSet,
               parent = "Cells",
               alias = "Single Cells",
               channels = c("FSC-A", "FSC-H")
)

# Compute spillover matrix
# blank will auto-overlay
spill <- cyto_spillover_compute(compenSet,
                                parent = "Single Cells",
                                spillover = "comp/Spillover-Matrix.csv"
)

# Visualise uncompensated data
cyto_plot_compensation(compenSet,
                       parent = "Single Cells")

# Visualise compensated data
cyto_plot_compensation(compenSet,
                       parent = "Single Cells",
                       spillover = "comp/Spillover-Matrix.csv",
                       compensate = TRUE)


# T cells --------
setwd('~/文档/liulab-data-analysis/00_util_scripts/CytometRy/230509/T/')
my_set <- "." |>
  cyto_setup(gatingTemplate = "gating_T.csv") |>
  # Apply compensation
  cyto_compensate(spillover = "../comp/Spillover-Matrix.csv") |>
  cyto_transform()

# right click to enclose the polygon
my_set |>
  cyto_gate_draw(
    parent = "root",
    alias = "cells",
    channels = c("FSC-A", "SSC-A"),
    contour_lines = 15
  )

my_set |>
  cyto_gate_draw(
    parent = "cells",
    alias = "single cells",
    channels = c("FSC-A","FSC-H")
  )

my_set |>
  cyto_gate_draw(
    parent = "single cells",
    alias = "live cells",
    type = 'rectangle',
    channels = c("FSC-A","7-AAD")
  )

unstain <- my_set |>
  cyto_extract('live cells') |>
  cyto_select(group = 'unstain')

my_set |>
  cyto_gate_draw(
    parent = "live cells",
    alias = c("CD4-T", "CD8-T"),
    type = 'rectangle',
    channels = c("CD4", "CD8a"),
    overlay = unstain
  )

my_set |>
  cyto_plot_gating_scheme(group_by = 'group',
                          gate_track = FALSE)

my_set |>
  cyto_plot(
    channels = c("CD4", "CD8a"),
    parent = 'live cells',
    alias = c("CD4-T", "CD8-T"),
    group_by = 'group',
    axes_limits = 'machine',
    layout = c(2,2)
  )

## stat compute and plot -----------
cyto_gatingTemplate_apply(my_set)

T_freq <- my_set |>
  cyto_stats_compute(parent = 'live cells',
                     alias = c("CD4-T", "CD8-T"),
                     stat = 'freq')

T_freq |>
  dplyr::filter(group != 'unstain') |>
  ggplot(aes(group, Frequency, color = group)) +
  stat_summary(geom = 'col', fun = 'mean', fill = 'white') +
  stat_summary(geom = 'errorbar', fun.data = 'mean_se', width = 0.3) +
  geom_jitter(height = 0, width = 0.1) +
  stat_compare_means(comparisons = list(c('IT','II'), c('IT','TT'), c('II', 'TT')),
                     method = 't.test')+
  theme_pubr() +
  labs_pubr(base_size = 16) +
  facet_wrap(~Population, scales = 'free') +
  ylab('Proportion in live cells (%)') 

# Myeloid cells --------
setwd('~/文档/liulab-data-analysis/00_util_scripts/CytometRy/230509/M')
'PE-CD3 BV421-CD11b FITC-CD11c APC-CD80+'
my_set <- "." |>
  cyto_setup(gatingTemplate = "gating.csv") |>
  # Apply compensation
  cyto_compensate(spillover = "../comp/Spillover-Matrix.csv") |>
  cyto_transform()

cyto_gatingTemplate_apply(my_set)

# right click to enclose the polygon
my_set |>
  cyto_gate_draw(
    parent = "root",
    alias = "cells",
    channels = c("FSC-A", "SSC-A")
  )

my_set |>
  cyto_gate_draw(
    parent = "cells",
    alias = "single cells",
    channels = c("FSC-A","FSC-H")
  )

my_set |>
  cyto_gate_draw(
    parent = "single cells",
    alias = "live cells",
    type = 'rectangle',
    channels = c("SSC-A","7-AAD"),
    contour_lines = 15
  )

unstain <- my_set |>
  cyto_extract('live cells') |>
  cyto_select(group = 'unstain')

my_set |>
  cyto_gate_draw(
    parent = "live cells",
    channels = c("CD3", "SSC-A"),
    alias = c("non-T cells"),
    overlay = unstain
  )

my_set |>
  cyto_gate_draw(
    parent = "non-T cells",
    alias = c("cDC", "mDC", "macrophages", "-"),
    type = 'quadrant',
    channels = c("CD11b", "CD11c"),
    overlay = unstain
  )

my_set |>
  cyto_gate_edit(
    parent = "macrophages",
    alias = "M1",
    type = 'rectangle',
    channels = c("CD80", "FSC-A"),
    overlay = unstain
  )

my_set |>
  cyto_plot(channels = c("CD11b", "CD11c"),
            parent = 'non-T cells',
            alias = c("cDC", "mDC", "macrophages"),
            group_by = 'group',
            axes_limits = 'machine',
            layout = c(2,2))

my_set |>
  cyto_plot(parent = "non-T cells",
            alias = "M1",
            channels = c("CD80", "FSC-A"),
            group_by = 'group',
            axes_limits = 'machine',
            #select = list(group = c('II','IT','TT')),
            layout = c(2,2))

my_set |>
  cyto_plot_gating_scheme(group_by = 'group',
                          gate_track = FALSE,
                          axes_limits = 'machine')

## stat compute and plot -----------
M_freq <- my_set |>
  cyto_stats_compute(parent = 'non-T cells',
                     alias = c("macrophages", "mDC", "cDC"),
                     stat = 'freq')

M_freq |>
  dplyr::filter(group != 'unstain') |>
  mutate(Population = fct_relevel(Population, 'cDC', 'mDC', 'macrophages')) |>
  ggplot(aes(group, Frequency, color = group)) +
  stat_summary(geom = 'col', fun = 'mean', fill = 'white') +
  stat_summary(geom = 'errorbar', fun.data = 'mean_se', width = 0.3) +
  geom_jitter(height = 0, width = 0.1) +
  stat_compare_means(comparisons = list(c('IT','II'), c('IT','TT'), c('II', 'TT')),
                     method = 't.test', label = 'p.signif')+
  theme_pubr() +
  labs_pubr(base_size = 16) +
  facet_wrap(~Population, scales = 'free') +
  scale_y_continuous(expand = expansion(mult = c(0, .1)), limits = c(0, NA)) +
  ylab('Proportion in non-T cells (%)') 

my_set |>
  cyto_stats_compute(parent = 'macrophages',
                     alias = c("M1"),
                     stat = 'freq') |>
  dplyr::filter(group != 'unstain') |>
  ggplot(aes(group, Frequency, color = group)) +
  stat_summary(geom = 'col', fun = 'mean', fill = 'white') +
  stat_summary(geom = 'errorbar', fun.data = 'mean_se', width = 0.3) +
  geom_jitter(height = 0, width = 0.1) +
  scale_y_continuous(expand = expansion(mult = c(0, .1)), limits = c(0, NA)) +
  stat_compare_means(comparisons = list(c('IT','II'), c('IT','TT'), c('II', 'TT')),
                     method = 't.test', label = 'p.signif')+
  theme_pubr() +
  labs_pubr(base_size = 16) +
  ylab('CD80+ cells in macrophages (%)') 

# B cells --------
setwd('~/文档/liulab-data-analysis/00_util_scripts/CytometRy/230510/B')

my_set <- "." |>
  cyto_setup(gatingTemplate = "gating.csv") |>
  # Apply compensation
  cyto_compensate(spillover = "../comp/Spillover-Matrix.csv") |>
  cyto_transform()

cyto_gatingTemplate_apply(my_set)

# right click to enclose the polygon
my_set |>
  cyto_gate_draw(
    parent = "root",
    alias = "cells",
    channels = c("FSC-A", "SSC-A"),
    contour_lines = 15
  )

my_set |>
  cyto_gate_draw(
    parent = "cells",
    alias = "single cells",
    channels = c("FSC-A","FSC-H")
  )

my_set |>
  cyto_gate_draw(
    parent = "single cells",
    alias = "live cells",
    type = 'rectangle',
    channels = c("SSC-A","7-AAD"),
    contour_lines = 15
  )

unstain <- my_set |>
  cyto_extract('live cells') |>
  cyto_select(group = 'unstain')

my_set |>
  cyto_gate_draw(
    parent = "live cells",
    alias = c("B cells", "Plasma cells"),
    type = 'rectangle',
    channels = c("B220", "CD138"),
    overlay = unstain
  )

# around 10*10 with cairo is ok for pdf canvas. preview is convinient for server
my_set |>
  cyto_plot(parent = "live cells",
            alias = c("B cells", "Plasma cells"),
            group_by = 'group',
            channels = c("B220", "CD138"),
            axes_limits = 'machine')

my_set |>
  cyto_plot_gating_scheme(group_by = "group",
                          gate_track = FALSE)

## stat compute and plot -----------
B_freq <- my_set |>
  cyto_stats_compute(parent = 'live cells',
                     alias = c("Plasma cells", "B cells"),
                     stat = 'freq')

B_freq |>
  dplyr::filter(group != 'unstain') |>
  ggplot(aes(group, Frequency, color = group)) +
  stat_summary(geom = 'col', fun = 'mean', fill = 'white') +
  stat_summary(geom = 'errorbar', fun.data = 'mean_se', width = 0.3) +
  geom_jitter(height = 0, width = 0.1) +
  stat_compare_means(comparisons = list(c('IT','II'), c('IT','TT'), c('II', 'TT')),
                     method = 't.test', label = 'p.signif')+
  theme_pubr() +
  labs_pubr(base_size = 16) +
  facet_wrap(~Population, scales = 'free') +
  scale_y_continuous(expand = expansion(mult = c(0, .1)), limits = c(0, NA)) +
  ylab('Proportion in live cells (%)')

